using System;
using Tools.Domain.Common.StateMachine;
using Webshop20.Domain.Orders.Core;
using Webshop20.Domain.Orders.Enumerations;
using System.Linq;
using Webshop20.Domain.Orders.Processes.Events;
using Webshop20.Domain.Orders.Processes.States;
using Webshop20.Domain.Shared.Payment.Core;

namespace Webshop20.Domain.Orders.Processes.Actions
{
    public class ExecuteOrderAction : IStateAction
    {
        public IState Execute(IStateEvent currentEvent, IStateContext context)
        {
            IState newState = new Pending();
            var orderProcess = context as OrderProcess;
            var executeOrderEvent = currentEvent as ExecuteOrderEvent;

            var attemptedReservations = executeOrderEvent.GoodTranslator.ConvertToAttemptedReservations(orderProcess.OrderInProgress.Positions);
            var failedReservations = executeOrderEvent.GoodReservationService.ReserveGoodsInStock(attemptedReservations);

            if(failedReservations.Count() > 0)
            {
                foreach (var failedReservation in failedReservations)
                {
                    executeOrderEvent
                        .AmazonDistributorService
                        .PlaceNewOrder(
                                        failedReservation.ExpectedReservations - failedReservation.ActualReservations, 
                                        failedReservation.ProductID
                                       );
                }

                newState = new AutoAquisition();
            }

            if (orderProcess.OrderInProgress.Payment is Prepayment)
            {
                newState = new OnHold();
            }


            var template = executeOrderEvent
                            .TemplateService.GetTemplate(
                                                            "NOTIFICATION_MAIL_TEMPLATE",
                                                            executeOrderEvent
                                                                .NotificationMailTranslator
                                                                .ConvertOrderDataToNameValues(orderProcess.OrderInProgress)
                                                         );
            executeOrderEvent.MailService.SendMail(orderProcess.OrderInProgress.PurchaserEMail, "Ihre Bestellung bei Webshop247", template);

            return newState;
        }
    }


}